package com.medicalfee.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.medicalfee.dao.ReimbursementList;
import com.medicalfee.dao.ReimbursementListDAO;

public class GetReimbursementListController implements Controller {
	private ReimbursementListDAO reimbursementListDao;

	public void setReimbursementListDao(
			ReimbursementListDAO reimbursementListDao) {
		this.reimbursementListDao = reimbursementListDao;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String hql = request.getParameter("hql");
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		int startPage = 0, limitNum = 0;
		if (start != null) {
			startPage = Integer.parseInt(start);
		}
		if (limit != null) {
			limitNum = Integer.parseInt(limit);
		}
		List reimbursementList = reimbursementListDao.getReimbursementList(hql,
				startPage, limitNum);
		int reimbursementSize = reimbursementList.size();
		JSONObject json = new JSONObject();
		JSONArray rows = new JSONArray();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJavaPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				if (name.equals("sid")) {
					return false;
				} else {
					return true;
				}
			}
		});
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new JsonValueProcessor() {
					public Object processObjectValue(String key, Object value,
							JsonConfig arg2) {
						if (value == null) {
							return "";
						}
						if (value instanceof Date) {
							return new SimpleDateFormat("yyyy-MM-dd")
									.format((Date) value);
						}
						return value.toString();
					}

					public Object processArrayValue(Object value,
							JsonConfig arg1) {
						return null;
					}
				});
		for (int i = 0; i < reimbursementSize; i++) {
			ReimbursementList reimbursement = (ReimbursementList) reimbursementList
					.get(i);
			JSONObject jobject = JSONObject.fromObject(reimbursement,
					jsonConfig);
			jobject.put("sid", reimbursement.getSid().getId());
			jobject.put("name", reimbursement.getSid().getName());
			rows.add(jobject);
		}
		json.put("total", reimbursementSize);
		json.put("rows", rows);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(json.toString());
		return null;
	}

}
